package com.demo.webapp.kcfinder.interceptor;

import com.demo.webapp.kcfinder.ActionMapping;
import com.demo.webapp.kcfinder.ActionProxy;
import com.demo.webapp.kcfinder.action.Action;
import com.demo.webapp.kcfinder.action.DownloadFileInfoAware;
import com.demo.webapp.kcfinder.context.ActionContext;
import com.demo.webapp.kcfinder.model.DownloadInfo;

/**
 * KCFinder文件下载拦截器
 * 针对文件(图片)的预览/下载提供文件信息FileInfo
 * @author ryuu.kk
 *
 */
public class KCFinderDownloadInterceptor implements Interceptor {

	@Override
	public String intercept(ActionProxy proxy, ActionMapping mapping) throws Exception {
		
		Action action = proxy.getAction();
		ActionContext context = ActionContext.getContext();
		
		String type = context.getValue("type", "images");
		String fileName = context.getValue("file", ""); 
		String dir = context.getValue("dir", context.getPublicPath());
		String stamp = context.getValue("stamp", "0");
		
		String contentType = getContentType(fileName.substring(fileName.lastIndexOf(".") + 1));
		
		DownloadInfo info = new DownloadInfo(dir, fileName, type, stamp);
		info.setContentType(contentType);
		
		if (DownloadFileInfoAware.class.isAssignableFrom(action.getClass())) {
			((DownloadFileInfoAware) action).setDwonloadInfo(info);
		}
		
		return null;
	}

	public static String getContentType(String exts ) {
		String contentType = "application/octet-stream";
		String extension = (exts != null && exts.length() > 0)? exts.trim() : "";
		if ("exe".equals(extension)) {
			contentType = "application/octet-stream";
		} else if ("doc".equals(extension)) {
			contentType = "application/msword";
		} else if ("txt".equals(extension)) {
			contentType = "txt/plain";
		} else if ("zip".equals(extension)) {
			contentType = "application/zip";
		} else if ("xml".equals(extension)) {
			contentType = "text/xml";
		} else if ("xls".equals(extension)) {
			contentType = "application/vnd.ms-excel";
		} else if ("png".equals(extension)) {
			contentType = "application/x-chess-pgn";
		} else if ("jpg".equals(extension) || "jpeg".equals(extension) || "bmp".equals(extension)) {
			contentType = "image/jpeg";
		} else if ("mp3".equals(extension)) {
			contentType = "audio/mpeg";
		} else if ("swf".equals(extension)) {
			contentType = "application/x-troff";
		} 
		return contentType;
	}
}
